package org.edu.modules.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.edu.common.api.vo.Result;
import org.edu.modules.common.entity.VeBaseCalendar;
import org.edu.modules.common.entity.VeBaseSemester;
import org.edu.modules.common.mapper.VeBaseCalendarMapper;
import org.edu.modules.common.mapper.VeBaseSemesterMapper;
import org.edu.modules.common.service.IVeBaseCalendarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class VeBaseCalendarServiceImpl extends ServiceImpl<VeBaseCalendarMapper, VeBaseCalendar> implements IVeBaseCalendarService {
    @Autowired
    private VeBaseCalendarMapper veBaseCalendarMapper;

    @Autowired
    VeBaseSemesterMapper veBaseSemesterMapper;

    public List<VeBaseCalendar> getCalendarListBySemId(Integer semId, Integer year, Integer month) {
        return this.veBaseCalendarMapper.getCalendarListBySemId(semId, year, month);
    }

    public VeBaseCalendar getCalenderByDates(String dates) {
        return this.veBaseCalendarMapper.getCalenderByDates(dates);
    }

    @Override
    @Transactional
    public Result<?> addCalendar(Integer semId) {
        //如果有生成，先删除生成的数据
        List<VeBaseCalendar> veBaseCalendarList = veBaseCalendarMapper.getBySemId(semId);
        if (veBaseCalendarList.size() > 0) {
            //如果有，先判断有没绑定到考勤，查考勤表
            List<VeBaseCalendar> calendars = veBaseCalendarMapper.getCalenderByStuCheck();
            if (calendars != null && calendars.size() > 0) {
                return Result.error("考勤已根据校历生成，无法重新生成校历，请先删除考勤数据");
            } else {
                //如果没有绑定，先删除，根据semId删除
                veBaseCalendarMapper.deleteBySemId(semId);
            }
        }
        //再重新添加数据
        //1.先查学期信息
        VeBaseSemester veBaseSemester = veBaseSemesterMapper.selectById(semId);
        if (veBaseSemester != null) {
            List<VeBaseCalendar> list = new ArrayList();
            //获取 开始时间和结束时间
            LocalDate startDate = timestampToLocalDate(veBaseSemester.getXqksrq());
            LocalDate endDate = timestampToLocalDate(veBaseSemester.getXqjsrq());
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 计算总天数差
            long totalDays = ChronoUnit.DAYS.between(startDate, endDate) + 1;
            // 生成每一天的条目
            for (int i = 0; i < totalDays; i++) {
                LocalDate currentDate = startDate.plusDays(i);
                DayOfWeek startDayOfWeek = startDate.getDayOfWeek();
                int startDayValue = startDayOfWeek.getValue(); // 1-7
                // 计算到下一个周一的天数偏移量
                int offset = (startDayValue == 1) ? 0 : (7 - (startDayValue - 1)) % 7;
                int weekNumber;
                if (i < offset) {
                    // 学期开始日期到下个周一前的天数，归属第1周
                    weekNumber = 1;
                } else {
                    // 对齐后，每7天为一周
                    weekNumber = ((i - offset) / 7) + 2;
                }
                // 格式化日期
                String formattedDate = currentDate.format(dateFormatter);
                //年
                int year = currentDate.getYear();
                //月
                int month = currentDate.getMonthValue();
                //周几
                int dayOfWeek = currentDate.getDayOfWeek().getValue();
                VeBaseCalendar veBaseCalendar = new VeBaseCalendar();
                veBaseCalendar.setSemId(semId);
                veBaseCalendar.setYear(year);
                veBaseCalendar.setMonth(month);
                veBaseCalendar.setDates(formattedDate);
                veBaseCalendar.setWeek(weekNumber);
                veBaseCalendar.setDayOfWeek(dayOfWeek);
                list.add(veBaseCalendar);
            }
            this.saveBatch(list);
        }
        return Result.ok("校历生成成功! ");
    }

    // 时间戳转LocalDate
    private static LocalDate timestampToLocalDate(long timestamp) {

        Instant instant = Instant.ofEpochSecond(timestamp);
        //使用系统默认时区
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate;
    }
}
